package com.hyl.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.google.common.eventbus.EventBus;
import com.hyl.IOrderDao;
import com.hyl.constans.Constants;
import com.hyl.domain.po.PayOrder;
import com.hyl.domain.req.ShopCartReq;
import com.hyl.domain.res.PayorderRes;
import com.hyl.domain.vo.ProductVO;
import com.hyl.service.rpc.ProductRPC;
import com.hyl.service.weixin.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

import static org.apache.logging.log4j.message.MapMessage.MapFormat.JSON;

/**
 * @author hyl
 * @description 订单服务实现类
 * @create 2025-06-06 16:07
 */
@Service
@Slf4j
public class OrderServiceImpl implements IOrderService {
    @Resource
    private IOrderDao iOrderDao;
    @Resource
    private ProductRPC productRPC;
    @Resource
    private AlipayClient alipayClient;
    @Value("${alipay.notify_url}")
    private String notifyUrl;
    @Value("${alipay.return_url}")
    private String returnUrl;
    @Resource
    private EventBus eventBus;

    @Override
    public PayorderRes creatOrder(ShopCartReq shopCartReq) throws AlipayApiException {
        //1.查询当前用户是否存在未支付订单或者掉订单
        PayOrder payOrderReq = new PayOrder();

        payOrderReq.setUserId(shopCartReq.getUserId());

        payOrderReq.setProductId(shopCartReq.getProductId());

        PayOrder unpayorder = iOrderDao.queryUnpayorder(payOrderReq);
        if(null != unpayorder && Constants.OrderStatusEnum.PAY_WAIT.getCode().equals(unpayorder.getStatus())){
            log.info("创建订单已经存在，存在未支付订单。userId：{},producrId:{}", shopCartReq.getUserId(),shopCartReq.getProductId());
            return PayorderRes.builder()
                    .orderId(unpayorder.getOrderId())
                    .payUrl(unpayorder.getPayUrl())
                    .build();
        } else if (null!= unpayorder && Constants.OrderStatusEnum.CREATE.getCode().equals(unpayorder.getStatus()) ) {
            //掉单的情况
            log.info("创建订单已经存在，存在掉单订单。userId：{},producrId:{}", shopCartReq.getUserId(),shopCartReq.getProductId());
            PayOrder payOrder = doPrepayOrder(unpayorder.getProductId(),unpayorder.getProductName(), unpayorder.getOrderId(),
                    unpayorder.getTotalAmount());
            return PayorderRes.builder()
                    .orderId(payOrder.getOrderId())
                    .payUrl(payOrder.getPayUrl())
                    .build();


        }
        //查询商品的情况，加上创建订单
        ProductVO productVO = productRPC.queryProductByProductId(shopCartReq.getProductId());
        String OrderId = RandomStringUtils.randomNumeric(16);
        iOrderDao.insert(PayOrder.builder()
                        .userId(shopCartReq.getUserId())
                        .productId(shopCartReq.getProductId())
                        .productName(productVO.getProductName())
                        .orderId(OrderId)
                        .totalAmount(productVO.getPrice())
                        .status(Constants.OrderStatusEnum.CREATE.getCode())
                        .createTime(new Date())
                        .orderTime(new Date())
                        .updateTime(new Date())
                .build());

        //创建支付订单
        PayOrder payOrder = doPrepayOrder(productVO.getProductId(),productVO.getProductName(),OrderId,
                productVO.getPrice());
        return PayorderRes.builder()
                .orderId(OrderId)
                .payUrl(payOrder.getPayUrl())
                .build();

        }

    @Override
    public void changeOrderPaySuccess(String orderId) {
        PayOrder payOrderReq = new PayOrder();
        payOrderReq.setOrderId(orderId);
        payOrderReq.setStatus(Constants.OrderStatusEnum.PAY_SUCCESS.getCode());
        log.info("更新订单状态，orderId={}, status={}", orderId, payOrderReq.getStatus());
        iOrderDao.changeOrderPaySuccess(payOrderReq);
        eventBus.post(com.alibaba.fastjson.JSON.toJSONString(payOrderReq));
    }

    @Override
    public List<String> queryNoPayNotifyOrder() {
        return iOrderDao.queryNoPayNotifyOrder();
    }

    @Override
    public List<String> queryTimeoutCloseOrderList() {
        return iOrderDao.queryTimeoutCloseOrderList();
    }

    @Override
    public boolean changeOrderClose(String orderId) {
        return iOrderDao.changeOrderClose(orderId);
    }


    private PayOrder doPrepayOrder(String productId, String productName, String orderId, BigDecimal totalAmount) throws
            AlipayApiException {
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(notifyUrl);
        request.setReturnUrl(returnUrl);

        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderId);
        bizContent.put("total_amount", totalAmount.toString());
        bizContent.put("subject", productName);
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        request.setBizContent(bizContent.toString());

        String form = alipayClient.pageExecute(request).getBody();

        PayOrder payOrder = new PayOrder();
        payOrder.setOrderId(orderId);
        payOrder.setPayUrl(form);
        payOrder.setStatus(Constants.OrderStatusEnum.PAY_WAIT.getCode());

        iOrderDao.updateOrderPayInfo(payOrder);

        return payOrder;

    }
}
